package com.lynx.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.lynx.mapper.cb.model.AndroidPluginPO;
import com.lynx.service.model.AndroidPluginBO;
import org.springframework.beans.factory.annotation.Autowired;

import com.lynx.mapper.cb.PluginStoreMapper;
import com.lynx.controller.model.AndroidPlugin;
import com.lynx.service.PluginStoreService;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * @author chris.liu
 * @version 4/10/14 9:58 AM
 */
@Service("pluginStoreService")
public class PluginStoreServiceImpl implements PluginStoreService {

	private static final int PAGE_SIZE = 2;

	@Autowired
	private PluginStoreMapper pluginStoreMapper;

	private int pluginNum = -1;

	@PostConstruct
	private void init() {
		try {
			pluginNum = pluginStoreMapper.getAndroidPluginNum();
		} catch (Exception e) {

		}
	}

	@Override
	public int getAndroidPluginPageSize() {
		if (pluginNum % PAGE_SIZE > 0) {
			return pluginNum / PAGE_SIZE + 1;
		} else {
			return pluginNum / PAGE_SIZE;
		}
	}

	@Override
	public List<AndroidPluginBO> getAndroidPlugins(int page) {

        int offset = (page - 1) > 0 ? (page - 1) * PAGE_SIZE : 0;
        List<AndroidPluginPO> pos = pluginStoreMapper.getAndroidPlugins(offset, PAGE_SIZE);

        List<AndroidPluginBO> bos = new ArrayList<AndroidPluginBO>();
        for (AndroidPluginPO po : pos) {
            bos.add(po2bo(po));
        }

		return bos;
	}

	@Override
	public boolean updatePlugin(AndroidPluginBO plugin) {
		try {
			pluginStoreMapper.updateAndroidPlugin(bo2po(plugin));
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	private AndroidPluginBO po2bo(AndroidPluginPO po) {
		AndroidPluginBO bo = new AndroidPluginBO();
		bo.setModule(po.getModule());
		bo.setVersion(po.getVersion());
		bo.setName(po.getName());
		bo.setDesc(po.getDesc());
		bo.setClazz(po.getClazz());
		bo.setIcon(po.getIcon());
		bo.setMd5(po.getMd5());
		bo.setCategory(po.getCategory());
		bo.setUrl(po.getUrl());
		return bo;
	}

	private AndroidPluginPO bo2po(AndroidPluginBO bo) {
		AndroidPluginPO po = new AndroidPluginPO();
		po.setModule(bo.getModule());
		po.setVersion(bo.getVersion());
		po.setName(bo.getName());
		po.setDesc(bo.getDesc());
		po.setClazz(bo.getClazz());
		po.setIcon(bo.getIcon());
		po.setMd5(bo.getMd5());
		po.setCategory(bo.getCategory());
		po.setUrl(bo.getUrl());
		return po;
	}

}
